package com.ryzx.jpa.helper.base;


import com.ryzx.common.response.BapException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.web.bind.annotation.*;

import java.lang.reflect.ParameterizedType;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

public class BapBaseController<T extends BapBaseEntity, ID > {

    @Autowired
    private BapBaseService<T,Long> bapBaseService;


    @PostMapping("/search")
    public <E extends BapBaseDTO> HashMap<String,Object> search(@RequestBody  E e){
        HashMap<String,Object> result=new HashMap<>();
        Page<T> p= bapBaseService.findAllToPage(e);
        result.put("records",p.getContent());
        result.put("total",p.getTotalElements());
        result.put("size",e.getPageSize());
        result.put("current",e.getPageNum());
        return result;
    }


    @PostMapping("")
    public T save(@RequestBody T t) {
        return bapBaseService.save(t);
    }
    @PutMapping("")
    public T update(@RequestBody T t){
        return bapBaseService.save(t);
    }

    @DeleteMapping("")
    public Boolean delete(@RequestBody List<String> ids) throws BapException {
        List<Long> ll= new ArrayList<>();
        for (String l:ids) {
            ll.add(Long.parseLong(l));
        }
        return bapBaseService.delByIds(ll);
    }

    @GetMapping("/{id}")
    private T findById(@PathVariable String id){
        return bapBaseService.findById(Long.valueOf(id)).orElse(null);
    }


    @SuppressWarnings("unchecked")
    private Class<T> getTClass() {
        return (Class<T>) ((ParameterizedType) this.getClass().getGenericSuperclass()).getActualTypeArguments()[0];
    }

}
